//
//  WebViewController.swift
//  worldexchange
//
//  Created by xionghao on 2019/1/9.
//  Copyright © 2019 xionghao. All rights reserved.
//

import UIKit
import QMUIKit

class WebViewController: QMUICommonViewController,WKUIDelegate,WKNavigationDelegate {

    @IBOutlet weak var webView: WKWebView!
    
    var articleItem:ArticleItem!
    
    var type:Int = 0
   
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
    }
    
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.setupHtmlData(item: articleItem)
    }
    
    
    func setupHtmlData(item:ArticleItem)  {
        self.showEmptyViewWithLoading()
        let locale = LanguageHelper.shareInstance.locale

        let fileName =  type == 0 ? "article" : "notitle"
        let path = Bundle.main.path(forResource: fileName, ofType: "html")
        var htmlstring = try! String(contentsOfFile:  path!, encoding: String.Encoding.utf8)
        var title:String!
        var content:String!
        if locale == "en" {
            title = item.etitle
            content = item.econtent
        }else if locale == "th" {
            title = item.ttitle
            content = item.tcontent
        }else {
            title = item.title
            content = item.content
        }
        self.title = title
        htmlstring =  htmlstring.replacingOccurrences(of: "{{title}}", with: title)
        htmlstring =  htmlstring.replacingOccurrences(of: "{{content}}", with: content)
        let baseUrl = URL(string: HOST_URL)!
        self.webView.loadHTMLString(htmlstring, baseURL: baseUrl)
        self.webView.uiDelegate = self
        self.webView.navigationDelegate = self
        
        self.hideEmptyView()
    }
    
  
    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if let url = navigationAction.request.url?.absoluteString {
            if url == HOST_URL + "/users/login.html" {
                decisionHandler(.cancel)
                if !isLogin {
                     Utils.pushLogin()
                }
                
            } else if url == HOST_URL + "/user/register.html" {
                if !isLogin {
                    Utils.pushRegister()
                }
                decisionHandler(.cancel)
            }else {
                decisionHandler(.allow)
            }
        }else {
            decisionHandler(.allow)
        }
       
    }

    
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
